using System;
using Gtk;
using ConferenceSystem;
using Socket = System.Net.Sockets.Socket;
using System.Threading;
using System.Collections.Generic;
using System.Net.Sockets;
using Midapex.Net.Ftp;
using Midapex.Net;
using FtpServer = Midapex.Net.Ftp.FtpServer;

public partial class MainWindow: Gtk.Window
{	
	private int readCount = 256;
	private static readonly object obj = new object();
	private bool ProcessFlag = true;
	private List<Socket> _list = new List<Socket>();
	FtpServer server = null;
	
	public MainWindow (): base (Gtk.WindowType.Toplevel)
	{
		Build ();
		InitProgram();
	}
	
	protected void OnDeleteEvent (object sender, DeleteEventArgs a)
	{
		server.Stop();
		Application.Quit ();
		a.RetVal = true;
	}
	
	protected void InitProgram()
	{
		server = new FtpServer();
		/*
         * 服务器的最大连接数
         */
        server.Capacity = 1000;

        /*
         * 连接超时时间
         */ 
        server.HeartBeatPeriod = 120000;  //120秒
        
        /*
         * 创建一个使用FTP的用户，
         */
        FtpUser user = new FtpUser("ftp");
        user.Password = "ftp";
        user.AllowWrite = true;
        user.HomeDir = @"D:\ftptemp";

        /*
         * 限制该帐号的用户的连接服务器的最大连接数
         * 也就是限制该使用该帐号的FTP同时连接服务器的数量。
         */
        user.MaxConnectionCount = 2;
        
        /*
         * 限制用户的最大上传文件为20M，超过这个值上传文件会失败。
         * 默认不限制该值，可以传输大文件。
         */ 
        user.MaxUploadFileLength = 1024 * 1024 * 20; 
        server.AddUser(user);

        //把当前目录作为匿名用户的目录，测试目的(必须指定)
        server.AnonymousUser.HomeDir= @"D:\ftptemp";
        
        server.Start();

	    //创建一个线程接收接收远程主机发来的信息
        //Thread mythread = new Thread(new ThreadStart(RecData));
        //将线程设为后台运行
        //mythread.IsBackground = true;
        //mythread.Start();
	}
	
#region tcp old
		
	protected void StartService()
	{
		TcpServer ts = new TcpServer(8080);		
		ts.Accept += delegate(object sender, System.Net.Sockets.Socket sock) 
		{
			try
			{
				sock.ReceiveTimeout = 10000;
				if(!sock.Connected)
				{
					return;
				}
				
				byte[] bs = new byte[readCount];
				NetworkStream _stream = new NetworkStream(sock);
				_stream.Read(bs, 0, readCount);
				string strCommand = System.Text.Encoding.Default.GetString(bs);
				//todo:获取命令结果
				//byte[] bResult = new byte[1024];
				byte[] bResult = LoadResult(strCommand);
				sock.Send(bResult);
				_stream.Close ();
				OutputMessage(sock.RemoteEndPoint.ToString ());
				//_list.Add(sock);
			}
			catch (Exception ex)
			{ 
				OutputMessage(ex.ToString());
			}
			finally
			{
				sock.Close();
			}
		};
		ts.Start();

	}
	
	protected byte[] LoadResult (string strCommand)
	{
		switch(strCommand)
		{
			case "w":
			return System.Text.Encoding.UTF8.GetBytes("<?xml />");
			default:
			return System.Text.Encoding.UTF8.GetBytes(string.Empty);
		}
	}

	protected void OutputMessage(string message)
	{
		lock(obj)
		{
			if(this.textview1.Buffer.Text.Length > 5000)
			{
				this.textview1.Buffer.Text = string.Empty;
			}
			message += "\r\n";
			this.textview1.Buffer.Text += message;
		}
	}
	
	protected void ProcessRequest()
	{
		while(ProcessFlag)
		{
			foreach(System.Net.Sockets.Socket item in _list)
			{
				ThreadPool.QueueUserWorkItem(SendQueryResult, item);
			}
		}
	}
	
	protected void SendQueryResult(System.Object state)
	{
		Socket s = state as Socket;
		if(!s.Connected)
		{
			_list.Remove(s);
			return;
		}
		
		NetworkStream _stream = new NetworkStream(s);
		if(!_stream.CanRead || !_stream.DataAvailable)
		{
			return;
		}
		
		byte[] bs = new byte[256];
		_stream.Read(bs, 0, 256);
		string strCommand = System.Text.Encoding.Default.GetString(bs);
		//todo:获取命令结果
		//byte[] bResult = new byte[1024];
		byte[] bResult = System.Text.Encoding.Default.GetBytes("结果.");
		s.Send(bResult);
	}
	#endregion
	
}
